import type { FormItem } from '@/components/FormDialog/data';
import ToeForm from '@/components/FormDialog/index';
import ToeUpload from '@/components/UploadDialog/index';
import {
  addLicense,
  customerCodeList,
  customerList,
  delLicense,
  delLicenses,
  getLicenseByPage,
  licenseExcelExport,
  updateLicense,
  updateLicensesCustomer,
  updateLicensesUser,
  uploadLicenseExcel,
} from '@/services/sales/license';
import { PlusOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Form, InputNumber, message, Modal, Select, Tag } from 'antd';

import { Spin } from 'antd';
import type { SelectProps } from 'antd/es/select';
import debounce from 'lodash/debounce';
import React, { useMemo, useRef, useState } from 'react';
import { useAccess, useLocation } from 'umi';

const { Option } = Select;

export interface DebounceSelectProps<ValueType = any>
  extends Omit<SelectProps<ValueType | ValueType[]>, 'options' | 'children'> {
  fetchOptions: (search: string) => Promise<ValueType[]>;
  debounceTimeout?: number;
}

function DebounceSelect<
  ValueType extends { key?: string; label: React.ReactNode; value: string | number } = any,
>({ fetchOptions, debounceTimeout = 800, ...props }: DebounceSelectProps<ValueType>) {
  const [fetching, setFetching] = useState(false);
  const [options, setOptions] = useState<ValueType[]>([]);
  const fetchRef = useRef(0);

  const debounceFetcher = useMemo(() => {
    const loadOptions = (value: string) => {
      fetchRef.current += 1;
      const fetchId = fetchRef.current;
      setOptions([]);
      setFetching(true);

      fetchOptions(value).then((newOptions) => {
        if (fetchId !== fetchRef.current) {
          // for fetch callback order
          return;
        }

        setOptions(newOptions);
        setFetching(false);
      });
    };

    return debounce(loadOptions, debounceTimeout);
  }, [fetchOptions, debounceTimeout]);

  return (
    <Select
      filterOption={false}
      onSearch={debounceFetcher}
      notFoundContent={fetching ? <Spin size="small" /> : null}
      {...props}
      options={options}
    />
  );
}

// Usage of DebounceSelect
interface UserValue {
  label: string;
  value: string;
}

async function fetchUserList(username: string): Promise<UserValue[]> {
  console.log('fetching user', username);
  return customerList({ blurry: username }).then((res) => {
    return res.data.map((item) => {
      return {
        label: item.name,
        value: item.id,
      };
    });
  });
}

async function fetchUserCodeList(username: string): Promise<UserValue[]> {
  console.log('fetching user', username);
  return customerCodeList({ blurry: username }).then((res) => {
    return res.data.map((item) => {
      return {
        label: item.code,
        value: item.id,
      };
    });
  });

  // return fetch('https://randomuser.me/api/?results=5')
  //   .then((response) => response.json())
  //   .then((body) =>
  //     body.results.map(
  //       (user: { name: { first: string; last: string }; login: { username: string } }) => ({
  //         label: `${user.name.first} ${user.name.last}`,
  //         value: user.login.username,
  //       }),
  //     ),
  //   );
}
const LicenseAdm: React.FC<{}> = () => {
  const [uploadVisit, setUploadVisit] = useState(false); //上传按钮显示
  const [formTitle, setFormTitle] = useState('新建授权号'); //
  const ref = useRef(null);
  const [formUserTitle, setFormUserTitle] = useState('授权'); //
  const [formUserVisit, setFormUserVisit] = useState(false); //
  const actionRef = useRef<ActionType>();
  const [formVisit, setFormVisit] = useState(false); // form表单设置
  const [formDisabled, setFormDisabled] = useState(false); //设置表单禁用
  const [form] = Form.useForm();
  const uploadRef = useRef(null);
  const formRef = useRef(null);
  const [userData, setUserData] = useState<object[]>([{ id: '', name: '' }]);
  const [value, setValue] = useState<UserValue[]>([]);
  const [selectRows, setSelectRows] = useState([]);
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable

  const [transNumMax, setTransNumMax] = useState(0);

  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  const access = useAccess();
  const onSelectChange = (newSelectedRowKeys: React.Key[], selectedRows) => {
    console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    console.log('selectedRowKeys changed: ', selectedRows);
    setSelectedRowKeys(newSelectedRowKeys);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  const location = useLocation();
  console.log(location, '---ceshi1---');

  // useEffect(() => {
  //   // Using an IIFE
  //   (async () => {
  //     const result = await userList({ blurry: null });
  //     setUserData(result?.data);
  //     console.log(result, '---result---');
  //   })();
  // }, []);

  // { value: 1, label: 'BD推广' },
  // { value: 2, label: '基础版' },
  // { value: 3, label: '尊享版' },
  // { value: 4, label: '高级版' },
  // { value: 5, label: '10Package' },
  // { value: 6, label: '50Package' },

  const licenseTypeMap = new Map([
    [1, 'BD推广'],
    [2, '基础版'],
    [3, '尊享版'],
    [4, '高级版'],
    [5, '10Package'],
    [6, '50Package'],
  ]);

  const statusMap = new Map([
    [true, '使用'],
    [false, '未使用'],
  ]);

  const statusMapColor = new Map([
    [true, 'red'],
    [false, 'green'],
  ]);

  /**
   * 穿梭框的数据设置
   */
  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 50,
    },
    {
      title: '唯一编号', //表头显示的名称
      search: false,
      dataIndex: 'identification', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      width: 150,
    },

    {
      title: '授权号类型', //表头显示的名称
      search: false,
      dataIndex: 'licenseType', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径

      render: (_, record) => <Tag color={'green'}>{licenseTypeMap.get(record.licenseType)}</Tag>,
    },
    {
      title: '使用状态',
      dataIndex: 'status',
      // hideInTable: true,
      valueType: 'select',
      render: (_, record) => (
        <Tag color={statusMapColor.get(record.status)}>{statusMap.get(record.status)}</Tag>
      ),
      valueEnum: {
        true: '使用',
        false: '未使用',
      },
    },

    {
      title: '授权号类型',
      dataIndex: 'licenseType',
      hideInTable: true,
      valueType: 'select',
      // [1, 'BD推广'],
      // [2, '基础版'],
      // [3, '尊享版'],
      // [4, '高级版'],
      // [5, '10Package'],
      // [6, '50Package'],
      valueEnum: {
        1: 'BD推广',
        2: '基础版',
        3: '尊享版',
        4: '高级版',
        5: '10Package',
        6: '50Package',
      },
    },
    {
      title: '授权号', //表头显示的名称
      // search: false,
      dataIndex: 'licenseID', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      width: 180,
    },
    {
      title: '订货号', //表头显示的名称
      search: true,
      dataIndex: 'orderId',
      valueType: 'select', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      width: 150,
      valueEnum: {
        '6PN20-1SWD02': '6PN20-1SWD02',
        '6PN20-1SWD02P': '6PN20-1SWD02P',
      },
    },
    {
      title: '备注', //表头显示的名称
      search: false,
      dataIndex: 'memo', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
    },

    {
      title: '购买时间', //表头显示的名称
      search: false,
      dataIndex: 'purchaseTime',
      width: 150,
    },

    {
      title: '购买时间', //表头显示的名称
      valueType: 'dateRange',
      hideInTable: true,
      dataIndex: 'purchaseTime',
    },

    {
      title: '使用时间', //表头显示的名称
      search: false,
      dataIndex: 'useTime',
      width: 150,
    },

    {
      title: '授权号数量', //表头显示的名称
      search: false,
      dataIndex: 'num', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      width: 110,
    },
    {
      title: '已用数量', //表头显示的名称
      search: false,
      dataIndex: 'usedNum', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      width: 150,
    },
    {
      title: '未使用数量', //表头显示的名称
      search: false,
      dataIndex: 'notUsedNum', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      width: 150,
    },
    {
      title: '所属客户', //表头显示的名称
      dataIndex: 'customerName', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      width: 120,

      search: false,
    },
    {
      title: '所属客户', //表头显示的名称
      dataIndex: 'customerId', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      width: 120,
      valueType: 'select',
      hideInTable: true,
      search: access.canAdmin() ? true : false,
      renderFormItem: (_, config, data) => {
        // 这里返回的值与Protable的render返回的值差不多,能获取到index,row,data 只是这里是获取对象组,外面会在包一层

        // 这个事v90
        return (
          <DebounceSelect
            showSearch
            placeholder="Select customers"
            fetchOptions={fetchUserList}
            // onChange={(newValue) => {
            //   setValue(newValue as UserValue[]);
            // }}
            style={{ width: '100%' }}
          />
        );
      },
    },
    // search: () => {
    //   if (access.canAdmin()) {
    //     return true;
    //   } else {
    //     return false;
    //   }
    // },

    {
      title: '创建人', //表头显示的名称
      search: false,
      dataIndex: 'createName',
      width: 80,
    },
    {
      title: '创建时间', //表头显示的名称
      search: false,
      dataIndex: 'createDate',
      width: 150,
    },

    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      hideInTable: !access.canAdmin() && !access.canChiefEngineer() ? true : false,
      render: (text, record, _, action) => {
        const buttonList = [];
        if (access.canAdmin() || access.canChiefEngineer()) {
          buttonList.push(
            <a
              key="editKey"
              onClick={() => {
                // console.log(record, '----测试----');
                // 编辑用户
                formRef.current.setFieldsValue({
                  ...record,
                });
                setFormTitle('编辑授权号');
                setFormDisabled(true);
                setFormVisit(true);
              }}
            >
              编辑
            </a>,
          );

          buttonList.push(
            <a
              key="deleteKey"
              onClick={() => {
                Modal.confirm({
                  title: '删除License',
                  content: '确定删除License',
                  okText: '确认',
                  cancelText: '取消',
                  onOk: async () => {
                    await delLicense({ id: record.id });
                    actionRef.current.reload();
                  },
                });
                // actionRef.current.reload();
              }}
            >
              删除
            </a>,
          );
        }

        return buttonList;
      },
    },
  ];
  const formColums: FormItem[] = [
    { field: 'id', label: 'id', hidden: true },
    { field: 'identification', label: 'identification', hidden: true },
    {
      field: 'licenseType',
      label: '授权号类型',
      type: 'select',
      disabled: true,
      options: [
        { value: 1, label: 'BD推广' },
        { value: 2, label: '基础版' },
        { value: 3, label: '尊享版' },
        { value: 4, label: '高级版' },
        { value: 5, label: '10Package' },
        { value: 6, label: '50Package' },
      ],
    },
    {
      field: 'licenseID',
      label: '授权号',
      disabled: true,
    },
    {
      field: 'orderId',
      label: '订货号',
      disabled: true,
    },
    {
      field: 'num',
      label: '授权号数量',
      type: 'inputNumber',
      value: 200,
      disabled: true,
    },
    {
      field: 'usedNum',
      label: '已用数量',
      type: 'inputNumber',
      value: 0,
      disabled: true,
    },
    {
      field: 'notUsedNum',
      label: '未用数量',
      type: 'inputNumber',
      value: 200,
      disabled: true,
    },

    {
      field: 'original',
      label: '授权号来源',
      value: 1,
      type: 'select',

      options: [
        { value: 1, label: 'GMC' },
        { value: 2, label: '转让' },
      ],
    },

    {
      field: 'originalName',
      label: '来源名称',
      value: '0000',
    },
    {
      field: 'nextGoing',
      label: '授权号去向',
      type: 'select',

      options: [
        { value: 1, label: 'GMC' },
        { value: 2, label: '转让' },
      ],
    },
    {
      field: 'memo',
      label: '备注',
    },
  ];

  const handleSubmit = async () => {
    if (formTitle == '新建授权号') {
      await addLicense(formRef.current.getFieldsValue());
    } else {
      await updateLicense(formRef.current.getFieldsValue());
    }
    setFormVisit(false);
    actionRef.current.reload();
    message.success('添加成功');
    // setModalVisit(false);
    // 这个爆红不用管(从新加载页面)
  };

  const handleSubmit2 = async () => {
    setConfirmLoading(true);
    if (selectRows.length <= 0) {
      return message.error('请先选择数据');
    }
    if (formUserTitle == '授权') {
      await updateLicensesUser({
        customerId: form.getFieldValue('customerId'),
        licenseIds: selectRows,
      });
    } else {
      await updateLicensesCustomer({
        customerId: form.getFieldValue('customerId'),
        licenseIds: selectRows,
        notUsedNums: form.getFieldValue('transNums'),
      });
    }

    setConfirmLoading(false);
    setFormUserVisit(false);
    message.success('添加成功');
    // actionRef.current.reset();
    actionRef.current.reload();
    actionRef.current.clearSelected();
    // setModalVisit(false);
  };
  return (
    <div>
      <PageContainer>
        <ProTable //表格Pro组件
          headerTitle="授权号查询" //表头
          actionRef={actionRef} //用于触发刷新操作等，看api
          formRef={ref}
          rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
          toolBarRender={(action, { selectedRows, selectedRowKeys }) => {
            if (access.canAdmin()) {
              return [
                <Button
                  key="button"
                  icon={<PlusOutlined />}
                  onClick={() => {
                    // console.log(selectedRows, '---选取多行----');
                    // 1.清空form
                    formRef.current.resetFields();
                    setFormDisabled(false);
                    setFormVisit(true);
                    setFormTitle('新建授权号');
                    //
                  }}
                  type="primary"
                >
                  新建
                </Button>,

                <Button
                  key="button"
                  icon={<PlusOutlined />}
                  onClick={() => {
                    // console.log(selectedRows, '---选取多行----');
                    // 1.清空form
                    setUploadVisit(true);
                  }}
                  type="primary"
                >
                  导入
                </Button>,
                <Button
                  key="button"
                  icon={<PlusOutlined />}
                  onClick={() => {
                    // console.log(selectedRows, '---选取多行----');
                    // 1.清空form
                    console.log(ref.current.getFieldsValue(), '----ref--');

                    licenseExcelExport({
                      current: 1,
                      pageSize: 5000,
                      ...ref.current.getFieldsValue(),
                    }).then((res) => {
                      const aLink = document.createElement('a');
                      document.body.appendChild(aLink);
                      aLink.style.display = 'none';
                      aLink.href = window.URL.createObjectURL(res);
                      aLink.setAttribute('download', `授权号${new Date()}.xlsx`);
                      aLink.click();
                      document.body.removeChild(aLink);
                    });
                  }}
                  type="primary"
                >
                  导出
                </Button>,

                <Button
                  key="button"
                  icon={<PlusOutlined />}
                  onClick={() => {
                    console.log(selectedRows, '---多行数据----');

                    // 1.清空form
                    if (selectedRowKeys == undefined || selectedRowKeys?.length <= 0) {
                      message.error('请先选择数据');
                    } else {
                      if (selectedRows.map((item) => item.status).includes(true)) {
                        message.error('有包含已经使用的授权号请重新选择');
                      } else {
                        setSelectRows(selectedRowKeys);
                        setFormUserVisit(true);
                        setFormUserTitle('授权');
                      }
                    }
                  }}
                  type="primary"
                >
                  授权
                </Button>,

                <Button
                  key="button"
                  icon={<PlusOutlined />}
                  onClick={() => {
                    Modal.confirm({
                      title: '删除License',
                      content: '确定删除License',
                      okText: '确认',
                      cancelText: '取消',
                      onOk: async () => {
                        await delLicenses(selectedRowKeys);
                        actionRef.current.reload();
                      },
                    });

                    // 1.清空form
                  }}
                  type="primary"
                >
                  删除
                </Button>,
              ];
            } else {
              return [
                <Button
                  key="button"
                  icon={<PlusOutlined />}
                  onClick={() => {
                    // console.log(selectedRows, '---选取多行----');
                    // 1.清空form
                    console.log(ref.current.getFieldsValue(), '----ref--');
                    licenseExcelExport({
                      current: 1,
                      pageSize: 5000,
                      ...ref.current.getFieldsValue(),
                    }).then((res) => {
                      const aLink = document.createElement('a');
                      document.body.appendChild(aLink);
                      aLink.style.display = 'none';
                      aLink.href = window.URL.createObjectURL(res);
                      aLink.setAttribute('download', `授权号${new Date()}.xlsx`);
                      aLink.click();
                      document.body.removeChild(aLink);
                    });
                  }}
                  type="primary"
                >
                  导出
                </Button>,
                <Button
                  key="button"
                  icon={<PlusOutlined />}
                  onClick={() => {
                    console.log(selectedRows, '---选取多行----');
                    // 1.清空form

                    // 1.清空form
                    if (selectedRowKeys == undefined || selectedRowKeys?.length <= 0) {
                      message.error('请先选择数据');
                    } else {
                      console.log(selectedRowKeys, '---选取多行----');
                      // 1.清空form
                      const notUsedNums = selectedRows
                        .map((item) => item.notUsedNum)
                        .reduce((item, item2) => item + item2);

                      console.log(notUsedNums, '---选取多行----');
                      setFormUserTitle('转让');
                      setSelectRows(selectedRowKeys);
                      setFormUserVisit(true);
                      setTransNumMax(notUsedNums);
                      form.setFieldsValue({
                        transNums: notUsedNums,

                        // type:record.type,
                        // sysPresetFlag:record.sysPresetFlag,
                      });
                    }
                  }}
                  type="primary"
                >
                  转让
                </Button>,
              ];
            }
          }}
          revalidateOnFocus={false}
          request={async (params = {}, sort, filter) => {
            let result;
            if (location.query.orderId === undefined || location.query.orderId === null) {
              result = await getLicenseByPage({ ...params });
            } else {
              result = await getLicenseByPage({ ...params, orderId: location.query.orderId });
            }

            console.log(result);
            return {
              data: result.data.content,
              total: result.data.totalElements,
              success: result.success,
            };
            // return  await new Promise({data:[{loginName:}], total:10, success: 0})
            // return {data:[], total:10, success: 0}
          }} //请求数据的地方，例子是用mock模拟数据，我是在后台请求的数据
          columns={columns} //上面定义的
          onDataSourceChange={(value) => {
            // 如果实在要保存新的值就需要在这边进行处理
            // console.log(value, selectedRowKeys, '---teee');
          }}
          rowSelection={rowSelection}
          pagination={{
            showSizeChanger: true,
          }}
          scroll={{ x: 2000, y: 350 }}
        />

        <Modal
          title={formUserTitle}
          visible={formUserVisit}
          onOk={handleSubmit2}
          confirmLoading={confirmLoading}
          onCancel={() => setFormUserVisit(false)}
        >
          <Form
            name="wrap"
            labelCol={{ flex: '110px' }}
            labelAlign="left"
            labelWrap
            form={form}
            wrapperCol={{ flex: 1 }}
            colon={false}
          >
            <Form.Item label="客户信息" name="customerId">
              {access.canAdmin() ? (
                <DebounceSelect
                  showSearch
                  value={value}
                  placeholder="Select customers"
                  fetchOptions={fetchUserList}
                  onChange={(newValue) => {
                    setValue(newValue as UserValue[]);
                  }}
                  style={{ width: '100%' }}
                />
              ) : (
                <DebounceSelect
                  showSearch
                  value={value}
                  placeholder="Select customers"
                  fetchOptions={fetchUserCodeList}
                  onChange={(newValue) => {
                    setValue(newValue as UserValue[]);
                  }}
                  style={{ width: '100%' }}
                />
              )}
            </Form.Item>

            <Form.Item label="转移数量" name="transNums">
              <InputNumber min={0} max={transNumMax} />
            </Form.Item>
          </Form>
        </Modal>
        <ToeForm
          visible={formVisit}
          title="新建授权号"
          disabled={formDisabled}
          ref={formRef}
          initialValues={{
            num: 200,
            usedNum: 0,
            notUsedNum: 200,
            original: 1,
            originalName: '0000',
          }}
          columns={formColums}
          onCancel={() => {
            setFormVisit(false);
          }}
          onOk={handleSubmit}
        />
        <ToeUpload
          onCancel={() => {
            setUploadVisit(false);
          }}
          ref={uploadRef}
          onOk={async () => {
            const formData = new FormData();
            console.log(uploadRef.current.fileList, '文件测试---');
            uploadRef.current.fileList.map((file) => {
              formData.append('file', file);
            });
            // formData.append('file', 'jja');
            console.log(formData, '---formData--');
            await uploadLicenseExcel(formData);
            actionRef.current.reload();
            setUploadVisit(false);
          }}
          visible={uploadVisit}
          title="文件上传"
        />
      </PageContainer>
    </div>
  );
};

export default LicenseAdm;
